<?php
/**	
 * 特采回货数量更新
 */
class Cron_Model_Backup_SpecialPurchase extends Model_Base {
	/**
	 * 获取指定sku下的状态为待采购和已采购的特采数据
	 * @param unknown $goods_sn
	 * @param unknown $warehouse_code
	 * @param unknown $platform_code
	 * @return unknown
	 */
	public function getSpecialPurchases($goods_sn,$warehouse_code,$platform_code) {
		$sql = "select id,apply_num,return_num,DATEDIFF(CURRENT_DATE,latest_time) as diff_day from p_special_purchase where goods_sn = :goods_sn and warehouse_code=:warehouse_code and platform_code=:platform_code and examine_status = 7 and purchase_status in (2,3) and latest_time >= :date order by latest_time asc,create_time asc";
		$params = [
			'goods_sn' => $goods_sn,
			'warehouse_code' => $warehouse_code,
			'platform_code' => $platform_code,
			'date'=>date("Y-m-d", strtotime('-1 day'))
		];
		$result = $this->db()->fetchAssoc($sql, $params);
		return $result;
	}
	/**
	 * 更新特采的回货数量和采购状态
	 * @param int $id
	 * @param unknown $return_num
	 * @param unknown $purchase_status
	 */
	public function returnSpecialGoods($id,$return_num,$purchase_status) {
		try {
			$this->db('write_db')->update('p_special_purchase', ['return_num'=>$return_num,'purchase_status'=>$purchase_status], 'id='.$id);
			$this->db('write_db')->insert('p_special_return_log',['sid'=>$id,'return_amount'=>$return_num,'return_date'=>date('Y-m-d')]);
		}catch (Exception $e) {
			throw $e;	
		}
	}
	/**
	 * 获取回货记录数
	 */
	public function getGoodsReturnAcount() {
		return $this->db()->fetchOne("select count(*) as total from p_special_purchase_return where date = :date and status=0", ['date'=>date("Y-m-d")]);
	}
	/**
	 * 获取回货记录
	 * @param unknown $start
	 * @param number $limit
	 * @return unknown
	 */
	public function getGoodsReturn($start, $limit = 100) {
		$sql = "select id,goods_sn,stock_sn,plat_code,back_quantity from p_special_purchase_return where date = :date and status=0 order by id asc limit ". $start ."," . $limit;
		$result = $this->db()->fetchAssoc($sql, ['date'=>date("Y-m-d")]);
		return $result;
	}
	/**
	 * 获取已通过，采购状态为待采购和部分采购，最迟回货时间在今天之后的特采
	 */
	public function getUnfinshPurchase() {
		$sql = "select goods_sn,warehouse_code,platform_code,(apply_num-return_num) as wait_num 
				from p_special_purchase where examine_status = 7 and purchase_status in (2,3) and latest_time >= current_date";
		return $this->db()->fetchAll($sql);
	}
	/**
	 * 设置回货记录为已计算
	 * @param unknown $id
	 * @param unknown $apply_num
	 * @param unknown $overtime_num
	 * @throws Exception
	 */
	public function finishGoodsReturn($id) {
		try {
			$this->db('write_db')->update('p_special_purchase_return',['status'=>1], 'id='.$id);
		}catch (Exception $e) {
			throw $e;	
		}
	}
}